<?php

/**
 * 处理咨询的生命流程 new=>replied=>wait_for_evaluation=>complete (cancelled)
 *
 * @author hongyang
 */
use Illuminate\Support\Facades\Event;
class QuestionWorkflowController extends QuestionController
{

    public $user;

    public function __construct()
    {
        parent::__construct();
        $user = Auth::user();
        $this->user = $user;
    }
    //创建免费咨询-验证
    public function createFree()
    {
        $type = 'question';
        $post = Input::all();
        $rules = array(
            'type' => array(
                'required',
                'regex:/^(question|pay_text|pay_phone|pay_company)$/i'
            )
        );
        $messages = array(
            'type.required' => '请选择咨询类型',
            'type.regex' => '咨询类型错误'
        );

        $post['type'] = $type;
        $validator = Validator::make($post, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        return $this->createFreeText();
    }
    //创建需要付费的咨询
    public function create($type)
    {
        $post = Input::all();
        $rules = array(
            'type' => array(
                'required',
                'regex:/^(question|pay_text|pay_phone|pay_company)$/i'
            )
        );
        $messages = array(
            'type.required' => '请选择咨询类型',
            'type.regex' => '咨询类型错误'
        );

        $post['type'] = $type;
        $validator = Validator::make($post, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        if (in_array($type, [
            Post::TYPE_PAY_PHONE,
            Post::TYPE_PAY_TEXT
        ])) {
            return $this->createPayTextAndPhone($post);
        } else
            return $this->createPayCompany();
    }

    /**
     * 创建法律顾问咨询
     */
    public function createPayCompany()
    {
        $input = Input::all();
        $rules = array(
            'content'   => 'required|between:2,1000',
            'lawyer_id' => 'required|exists:lawyer,user_id',
            'product_id'   => 'required',
        );
        $messages = array(
            'content.required' => '请填写咨询内容',
            'content.between' => '咨询内容长度在:min到:max之间',
            'lawyer_id.required' => '请提交律师id',
            'lawyer_id.exists' => '该律师不存在',
            'product_id.required' => '请填写咨询卡种',
        );
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            return $this->makeView('errors.400', $validator->errors(), 400);
        }
        try {
            $new_post = DB::transaction(function ($input) use ($input) {
                $product = Product::find($input['product_id']);
                $lawyer = Lawyer::find($input['lawyer_id']);
                $qty = ($product->id == 1) ? 2 : 1;
                $order_model = App::make('Order');
                $order_model->user_id = Auth::user()->id;
                $order_model->price = $product->price * $qty;
                $order_model->qty = $qty;
                // $order_model->phone = $input['contact_phone'];
                $order_model->memo = "";
                $order_model->workflow_id = 0;
                $order_model->pay_status = 0;
                $order_model->state = Order::STATE_INIT;
                $order_model->title = $product->name;
                $order_model->save();
                $data = array(
                    'title' => $product->name,
                    'content' => $input['content'],
                    'type' => Post::TYPE_PAY_COMPANY
                );
                $new_post = Post::storePayQuestion($data);
                $new_post->assignToLawyer($lawyer->user_id);
                $new_post->assignToOrder($order_model->id);
                $input['order_id'] = $order_model->id;
               //$new_company = CompanyServer::_create($input);
                $work_flow = App::make('Workflow');
                $work_flow->order_id = $order_model->id;
                $work_flow->workflow_node_id = WorkflowNode::where('act_order', 1)->pluck('id');
                $work_flow->user_id = Auth::user()->id;
                $work_flow->user_name = Auth::user()->realname ? Auth::user()->realname : Auth::user()->id;
                $work_flow->memo = '';
                $work_flow->save();

                // 保存order item

                $product = App::make('Product')->find($input['product_id']);
                $order_item_model = App::make('OrderItem');
                $order_item_model->order_id = $order_model->id;
                $order_item_model->product_id = $input['product_id'];
                $order_item_model->price = $product->price;
                $order_item_model->qty = $qty;
                $order_item_model->save();

                return $new_post;
            });
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '服务器暂时无法响应，请稍后再试', 503);
        }

        return $this->makeView('general.201', $new_post->id, 201);
    }

    /**
     * 创建付费图文咨询
     * @param $params
     */
    public function createPayTextAndPhone($params)
    {
        $rules = array(
            //'title' => 'required',
            'content' => 'required|between:2,1000',
            //'cat_id' => 'required',
            //'file_paths' => 'array',
            'lawyer_id' => 'required|exists:lawyer,user_id'
        );
        $messages = array(
            //'title.required' => '请填写咨询标题',
            'content.required' => '请填写咨询内容',
           // 'cat_id.required' => '请选择法律类别',
            //'file_paths.array' => '上传的文件列表要是数组的格式',
            'content.between' => '咨询内容长度在:min到:max之间',
            'lawyer_id.required' => '请提交律师id',
            'lawyer_id.exists' => '该律师不存在'
        );

        $validator = Validator::make($params, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }
        try {
            $new_post = DB::transaction(function ($params) use ($params) {
                // 保存咨询
                $post = UtilsHelper::filter_sensitive_word($params); // 敏感词过滤
                //$post['post_category'] = $post['cat_id'];
                $new_post = Post::storePayQuestion($post);
                $new_post->load('postExtra', 'comments');
                $lawyer = Lawyer::find($post['lawyer_id']);
                $price = '';
                if ($new_post->type == Post::TYPE_PAY_TEXT) {
                    $price = $lawyer->text_reply_fee;
                }
                if ($new_post->type == Post::TYPE_PAY_PHONE) {
                    $price = $lawyer->phone_reply_fee;
                }
                $order = new Order();
                $order->user_id = Auth::user()->id;
                $order->price = $price;
                //$order->title = $post['title'];
                $order->phone = isset($post['phone']) ? $post['phone'] : Auth::user()->phone;
                $order->qty = 1;
                $order->workflow_id = 0;
                $order->state = Order::STATE_INIT;
                $order->pay_status = 0;
                $order->save();
                $new_post->assignToLawyer($lawyer->user_id);
                $new_post->assignToOrder($order->id);
                UserScoresHistory::post();
                return $new_post;
            });
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '咨询律师失败，请稍后再试。', 503);
        }
        return $this->makeView('general.201', $new_post->id, 201);
    }

    /**
     * 创建免费图文咨询
     */
    public function createFreeText()
    {
        if (Input::server('REQUEST_METHOD') == 'POST') {
            if (isset($this->user) && $this->user->status == User::STATUS_VERIFIED_LAWYER) {
                return $this->makeView('errors.403', '律师用户没有权限创建资讯。', 403);
            }

            $post = Input::all();
            $rules = array(
                'title' => 'required',
                'content' => 'required|between:2,1000',
                'cat_id' => 'required',
                'file_paths' => 'array'
            );
            $messages = array(
                'title.required' => '请填写咨询标题',
                'content.required' => '请填写咨询内容',
                'cat_id.required' => '请选择法律类别',
                'file_paths.array' => '上传的文件列表要是数组的格式',
                'content.between' => '咨询内容长度在:min到:max之间'
            );

            $validator = Validator::make($post, $rules, $messages);
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView('errors.400', $validator->errors(), 400);
            }

            // 验证成功
            try {
                // 保存咨询
                $post = UtilsHelper::filter_sensitive_word($post); // 敏感词过滤
                $post['post_category'] = $post['cat_id'];
                $new_post = Post::storeQuestion($post);
                $new_post->load('attachments', 'postExtra');
            } catch (Exception $ex) {
                Log::error($ex);
                return $this->makeView('errors.503', '咨询律师失败，请稍后再试。', 503);
            }
            //免费咨询事件
            Event::fire('create_free_question', [$new_post, $post]);
            //Result
            return $this->makeView('general.201', ['post_id' => $new_post->id], 201);
        } else {
            $this->makeView('question.public.list');
        }
    }

    /**
     * 创建咨询
     */
    public function createForm()
    {
        $this->makeView('question.create_form');
    }

     /**
     * 公益咨询-列表
     */
    public function publicList()
    {
        $this->makeView('question.public.list');
    }
     /**
     * 公益咨询-提问
     */
    public function publicCommit()
    {
        $this->makeView('question.public.commit');
    }
     /**
     * 公益咨询-打赏支付
     */
    public function publicReward($id)
    {
        $this->makeView('question.public.reward',['id' => $id]);
    }
    /**
     * 公益咨询-详情
     */
    // public function publicView($id) {
    //     $post = $this->getQuestion($id);

    //     if (!is_a($post, 'Post')) {
    //         return $post;
    //     }
    
    //     $post->load('postExtra', 'comments');

    //     $postArr = $post->toArray();

    //     foreach($postArr['comments'] as &$comments) {
    //         $creatorId = $comments['creator_id'];
    //         $creator = User::find($creatorId);
    //         $creator->load('lawyer');
    //         $owner = $creator->toArray();
    //         $comments['creator_id'] = $owner['id'];
    //         $comments['creator_avatar'] = UtilsHelper::getImage($owner['avatar'], "img/dfimg.png");
    //         $comments['creator_name'] = $owner['realname'];
    //         $comments['creator_company_name'] = $owner['lawyer']['company_name'];
    //         $comments['creator_practice_period'] = UtilsHelper::getPracticePeriodStr($owner['lawyer']['practice_period']);
    //         $comments['creator_average_evaluate_score'] = $owner['lawyer']['average_evaluate_score'];
    //         $comments['creator_case_count'] = $owner['lawyer']['case_count'];

    //         // $comments['owner'] = $creator->toArray();
    //         // $comments['owner']['avatar'] = UtilsHelper::getImage($comments['owner']['avatar'], "img/dfimg.png");
    //         $comments['from_creator'] = (bool) ($postArr['creator_id'] == $comments['creator_id']);
    //     }
    //     if (Auth::user() ) {
    //         $postArr['is_collect'] = Collect::where('item_id', $id)->where('collect_type', Collect::TYPE_ARTICLE)->where('creator_id', Auth::user()->id)->first();
    //     } else {
    //         $postArr['is_collect'] = false;
    //     }
    //     if (Auth::user() && $post->canReply(Auth::user()->id, $postArr['status'])) {
    //         $postArr['can_reply'] = true;
    //     } else {
    //         $postArr['can_reply'] = false; 
    //     }
    //     if (Auth::user()) {
    //         $postArr['confirm'] = ($postArr['creator_id'] == Auth::user()->id && $postArr['status'] == Post::STATUS_WAIT_FOR_EVALUATION);
    //     }
    //     if(Auth::check())
    //     {
    //         $postArr['is_collect'] = Collect::collected_post($post);
    //     }

    //     $postCreator = User::find($postArr['creator_id']);
    //     $postCreatorArr = $postCreator->toArray();
    //     $postArr['creator_avatar'] = UtilsHelper::getImage($postCreatorArr['avatar'], "img/dfimg.png");
    //     $postArr['creator_realname'] = $postCreator['realname'];

    //     try {
    //         // 增加浏览次数
    //         $postExtra = $post->postExtra()->first();
    //         if (!$postExtra) {
    //             $postExtra = new PostExtra();
    //             $postExtra->views_count = 0;
    //             $postExtra->comments_count = 0;
    //             $postExtra->likes_count = 0;
    //             $postExtra->collects_count = 0;
    //             $postExtra->last_comment_user_id = 0;
    //             $post->postExtra()->save($postExtra);
    //         }

    //         $postExtra->increment('views_count');
    //         $postExtra->touch();
    //         $postExtra->save();
    //     } catch(Exception $ex) {
    //         Log::error($ex);
    //         return $this->makeView(
    //             'errors.503', 
    //             '请稍后再试。',
    //             503
    //         );
    //     }
    //     return $this->makeView('question.public.view', $postArr);
    //     //     return $this->makeView('question.public.view', ['id' => $id]);
    // }


     /**
     * 一对一咨询-列表
     */
    public function majorList()
    {
        $this->makeView('question.major.list');
    }
     /**
     * 一对一咨询-图文详情
     */
    public function textView()
    {
        $this->makeView('lawyer.text_view');
    }
    /**
     * 一对一咨询-电话详情
     */
    public function phoneView()
    {
        $this->makeView('lawyer.phone_view');
    }

    /**
     * 一对一咨询-填写详情
     */
    public function fillInView($id)
    {
        $this->makeView('lawyer.fill_in_view',['id' => $id]);
    }



    /**
     * 上传咨询相关的图片
     */
    public function upfiles()
    {
        $field_name = 'files';

        // upload avatar
        $rules = array(
            'files' => 'required'
        );
        $messages = array(
            'files.required' => '请上传文件'
        );

        $posts = Input::all();

        $validator = Validator::make ( $posts, $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400',
                $validator->errors(),
                400
            );
        }

        $file_name = $_FILES['files']['name'];
        $type_arr = explode('.', $file_name);
        $type = end($type_arr);
        $allow_exts = [
            'jpg',
            'jpeg',
            'jpe',
            'png',
            'gif',
            'bmp'
        ];
        if (! in_array(strtolower($type), $allow_exts)) {
            return $this->makeView('errors.400', '文件格式不正确，职能上传图片', 400);
        }
        if ($_FILES['files']['size'] > 2097152) {
            return $this->makeView('errors.400', '文件不能超过2M', 400);
        }
        $upload_folder = Config::get('app.upload_dir') . '/question_img/' . date('Y') . '/' . date('m') . '/';
        $full_upload_folder = UploadHelper::getFileFolder($upload_folder);

        try {

            if (! is_dir($full_upload_folder)) {
                mkdir($full_upload_folder, 0777, true);
            }
            $result = UploadHelper::upload($field_name, $full_upload_folder, $allow_exts);
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '上传失败，请稍后再试。', 503);
        }
        $file_path = $upload_folder . "/" . $result['files'][0]['basename'] . "." . $result['files'][0]['ext'];
        return $this->makeView('general.200', array(
            'file_path' => $file_path,
            'file_name' => $file_name
        ), 200);
    }

    // public function pay($id)
    // {
    //     $post = $this->getQuestion($id);
    //     if (! is_a($post, 'Post')) {
    //         return $post;
    //     }
    //     // 检查咨询的状态check status of the question
    //     Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
    //         return (bool) ($post->status == Post::STATUS_WAIT_PAY);
    //     });

    //     $rules = array(
    //         'post_id' => 'task_status'
    //     );
    //     $messages = array(
    //         'post_id.task_status' => '这个咨询的状态不正确'
    //     );
    //     $input['post_id'] = $id;
    //     $validator = Validator::make($input, $rules, $messages);
    //     if ($validator->fails()) {
    //         // the given data did not pass validation
    //         return $this->makeView('errors.400', $validator->errors(), 400);
    //     }

    //     $wallet = Wallet::where('user_id', Auth::user()->id)->first();
    //     $order = $post->getOrder($id);
    //     $data = [];
    //     $data['post_id'] = $id;
    //     $data['type'] = $post->getType();
    //     $data['price'] = round($order->price);
    //     $data['order_no'] = $order->order_no;
    //     $data['status'] = $post->getStatus();
    //     $data['title'] = $post->title;
    //     $data['content'] = $post->content;
    //     $data['updated_at'] = $post->updated_at;
    //     $data['created_at'] = $post->created_at;
    //     $data['lawyer'] = $post->getLawyerName();
    //     $data['money'] = round($wallet ? $wallet->money : 0);

    //     // return $this->makeView('center.customer.order.pay', $data);
    //     // TODO: 下面要用支付系统
    // }

    /**
     * 律师抢单
     */
    public function take($id)
    {
        $post = $this->getQuestion($id);
        if (! is_a($post, 'Post')) {
            return $post;
        }

        if ($this->user->status != User::STATUS_VERIFIED_LAWYER) {
            return $this->makeView('errors.403', '只有律师用户可以抢单。', 403);
        }

        // 咨询要在律师的工作范围里面
        $input = Input::all();
        Validator::extend('task_exists', function ($attr, $value, $parameters) use ($post) {
            $site_lawyer_conf = Config::get('site.company_lawyers');
            if (in_array($this->user->id, $site_lawyer_conf)) {
                return true;
            }

            if ($post->type == Post::TYPE_QUESTION) {
                // 律师的长处要和咨询的类别匹配
                $user = User::find(Auth::user()->id);
                $user->load('lawyer');
                $userArr = $user->toArray();
                $workScopeStr = $userArr['lawyer']['work_scope'];
                $workScopeArr = explode(",", $workScopeStr);
                return in_array($post->post_category, $workScopeArr);
            }

            return false;
        });

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->status == Post::STATUS_NEW);
        });

        // 检查咨询的类型，只有两种咨询可以抢单
        Validator::extend('type_check', function ($attr, $value, $parameters) use ($post) {
            return in_array($post->type, [
                Post::TYPE_QUESTION,
                Post::TYPE_PAY_COMPANY
            ]);
        });

        $rules = array(
            'post_id' => 'type_check|task_status|task_exists'
        );
        $messages = array(
            'post_id.task_exists' => '这个咨询并没有被推送给律师',
            'post_id.task_status' => '这个咨询的状态不正确',
            'post_id.type_check' => '这个咨询不能抢单'
        );
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        // 所有验证成功, 改变咨询的状态，并把咨询加入到post_thread里面，使其和律师建立1对1的联系
        try {
            $post->status = Post::STATUS_REPLIED;
            $post->save();
            $post->assignToLawyer(Auth::user()->id);
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '抢单失败，请稍后再试。', 503);
        }
        return $this->makeView('general.200', '成功抢单', 200);
    }

    /*
     * 接收订单
     */
    public function accept($id)
    {
        $post = $this->getQuestion($id);
        if (! $post) {
            return $post;
        }

        if ($this->user->status != User::STATUS_VERIFIED_LAWYER) {
            return $this->makeView('errors.403', '当前用户没有权限访问这个接口。', 403);
        }

        // 咨询要在律师的工作范围里面
        $input = Input::all();
        Validator::extend('assigned_to_lawyer', function ($attr, $value, $parameters) use ($post) {
            return $post->isAssignedToLawyer($this->user->id);
        });

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->status == Post::STATUS_NEW);
        });

        $rules = array(
            'post_id' => 'assigned_to_lawyer|task_status'
        );
        $messages = array(
            'post_id.assigned_to_lawyer' => '这个咨询并没有被指定给律师',
            'post_id.task_status' => '这个咨询的状态不正确'
        );
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        try {
            $post->status = Post::STATUS_REPLIED;
            $post->save();
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '请求失败，请稍后再试。', 503);
        }
        Event::fire('lawyer_accept', [$post]);
        return $this->makeView('general.200', '接单成功', 200);
    }

    /*
     * 拒绝订单
     */
    public function refuse($id)
    {
        $post = $this->getQuestion($id);
        if (! $post) {
            return $post;
        }

        if ($this->user->status != User::STATUS_VERIFIED_LAWYER) {
            return $this->makeView('errors.403', '当前用户没有权限访问这个接口。', 403);
        }

        // 咨询要在律师的工作范围里面
        $input = Input::all();
        Validator::extend('assigned_to_lawyer', function ($attr, $value, $parameters) use ($post) {
            return $post->isAssignedToLawyer($this->user->id);
        });

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->status == Post::STATUS_NEW);
        });

        $rules = array(
            'post_id' => 'assigned_to_lawyer|task_status'
        );
        $messages = array(
            'post_id.assigned_to_lawyer' => '这个咨询并没有被指定给律师',
            'post_id.task_status' => '这个咨询的状态不正确'
        );
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        try {
            $post->status = Post::STATUS_CANCELLED;
            $post->save();

            $user_id = Post::find($id)->creator_id;
            $order_id = PostOrder::where('post_id', $id)->first()->order_id;
            $price = Order::find($order_id)->price;
            $userWallet = Wallet::getWallet($user_id);
            $userWallet->money = $userWallet->money + $price;

            $walletTransaction = WalletTransaction::getWalletTransaction($user_id, WalletTransaction::TYPE_QUESTION, $order_id, WalletTransaction::DIRECTION_OUT);

            if ($walletTransaction) {
                $walletTransaction->status = WalletTransaction::STATUS_FAIL;
                $walletTransaction->result = "该订单已被拒绝，费用已返还到您的钱包";
            }
            DB::transaction(function () use ($userWallet, $walletTransaction) {
                $userWallet->save();
                if ($walletTransaction) {
                    $walletTransaction->save();
                }
            });
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '请求失败，请稍后再试。', 503);
        }

        return $this->makeView('general.200', '拒绝成功', 200);
    }

    /**
     * 确定已完成
     *
     * @param int $id
     */
    public function confirm($id)
    {
        $post = $this->getQuestion($id);
        if (! is_a($post, 'Post')) {
            return $post;
        }
        Validator::extend('is_creator', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->creator_id == Auth::user()->id);
        });

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->status == Post::STATUS_REPLIED);
        });

        $rules = array(
            'post_id' => 'required|is_creator|task_status'
        );
        $messages = array(
            'post_id.required' => '请提交咨询的id',
            'post_id.task_status' => '这个咨询的状态不正确',
            'post_id.is_creator' => '只有咨询的创建者才可以完成咨询'
        );
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }
        try {
            $post->status = Post::STATUS_WAIT_FOR_EVALUATION;
            $post->save();
            $lawyer = $post->getLawyerName();
            if ($lawyer) {
                $lawyer = Lawyer::find($lawyer->id);
            }
            // 如果付费咨询，更改相应订单状态，将钱返还到律师钱包，并增加流水账目
            if ($post->type == Post::TYPE_PAY_TEXT || $post->type == Post::TYPE_PAY_PHONE || $post->type == Post::TYPE_PAY_COMPANY) {
                $order = $post->getOrder($id);
                $order->state = Order::STATE_DONE;
                DB::transaction(function () use ($lawyer, $order) {
                    $order->save();
                    // 更改用户的流水记录状态
                    $user_walletTransaction = WalletTransaction::getWalletTransaction(Auth::user()->id, WalletTransaction::TYPE_QUESTION, $order->order_no, WalletTransaction::DIRECTION_OUT);
                    $user_walletTransaction->status = WalletTransaction::STATUS_SUCCESS;
                    $user_walletTransaction->save();
                    // 创建一条律师用户的流水记录
                    if ($lawyer) {
                        $lawyer->increment("pay_reply_count");
                        $lawyer->save();
                        $lawyer_wallet = Wallet::getWallet($lawyer->user_id);
                        $lawyer_wallet->money = $lawyer_wallet->money + $order->price;
                        $lawyer_wallet->save();
                        $data = array(
                            'user_id' => $lawyer->user_id,
                            'type' => WalletTransaction::TYPE_QUESTION,
                            'direction' => WalletTransaction::DIRECTION_IN,
                            'associate_id' => $order->order_no,
                            'order_no' => $order->order_no,
                            'status' => WalletTransaction::STATUS_SUCCESS,
                            'sum' => $order->price,
                            'description' => "来自" . Auth::user()->realname . "用户的付费咨询",
                            'result' => ''
                        );
                        $lawyer_walletTransaction = WalletTransaction::storeWalletTransaction($data);
                    }
                });
            } else {
                $lawyer->increment("free_reply_count");
                $lawyer->save();
            }
            // 结束订单状态的更改
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '请求失败，请稍后再试。', 503);
        }

        return $this->makeView('general.200', '确定完成', 200);
    }

    /**
     * 评价咨询
     *
     * @param int $id
     */
    public function evaluate($id)
    {
        $post = $this->getQuestion($id);
        if (! is_a($post, 'Post')) {
            return $post;
        }
        Validator::extend('is_creator', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->creator_id == Auth::user()->id);
        });

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->status == Post::STATUS_WAIT_FOR_EVALUATION);
        });

        Validator::extend('invalid_tags', function ($attr, $value, $parameters) use ($post) {
            $valid_tags = Evaluate::getAvailableEvaluateTags();
            foreach ($value as $tag) {
                if (! array_key_exists($tag, $valid_tags)) {
                    return false;
                }
            }
            return true;
        });

        $rules = array(
            'evaluate_score' => 'required|integer|between:1,5',
            'evaluate_comment' => 'required',
            'evaluate_tags' => 'array'
        );
        $messages = array(
            'evaluate_score.required' => '请输入从1到5的评价的分数',
            'evaluate_comment.required' => '请输入评价内容',
            'evaluate_score.integer' => '评价的分数只能是数字',
            'evaluate_score.between' => '评价的分数只能是1到5的数字',
            'evaluate_comment.is_creator' => '只有咨询的人才可以评论',
            'evaluate_comment.task_status' => '该咨询不可以评价',
            'evaluate_tags.array' => '快速评价的数据需要是数组',
            'evaluate_tags.invalid_tags' => '快速评价的标签不被支持'
        );
        $input = Input::all();
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        $input = UtilsHelper::filter_sensitive_word($input);

        try {
            $post->status = Post::STATUS_COMPLETE;
            $post->save();
            $tags_str = implode(",", $input['evaluate_tags']);
            Evaluate::addEvaluation($post, $input['evaluate_score'], $input['evaluate_comment'], $tags_str);
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '请求确认失败，请稍后再试。', 503);
        }
        Event::fire('evaluate',$post);
        return $this->makeView('general.200', $post->toArray(), 200);
    }

    /**
     * 评价咨询
     */
    public function tip($id)
    {
        $post = $this->getQuestion($id);
        if (! is_a($post, 'Post')) {
            return $post;
        }
        Validator::extend('is_creator', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->creator_id == Auth::user()->id);
        });

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->status == Post::STATUS_WAIT_FOR_EVALUATION);
        });

        Validator::extend('type_check', function ($attr, $value, $parameters) use ($post) {
            return (bool) ($post->type == Post::TYPE_QUESTION);
        });

        $rules = array();
        // 'evaluate_score' => 'required|integer|between:1,5',
        // 'evaluate_comment' => 'required|is_creator|task_status|type_check'

        $messages = array(
            'evaluate_score.required' => '请输入从1到5的评价的分数',
            'evaluate_score.integer' => '评价的分数只能是数字',
            'evaluate_score.between' => '评价的分数只能是1到5的数字',
            'evaluate_comment.required' => '请输入评价的内容',
            'evaluate_comment.is_creator' => '只有咨询的人才可以评论',
            'evaluate_comment.task_status' => '该咨询不可以评价',
            'evaluate_comment.type_check' => '只有免费资讯才可以送心意'
        );
        $input = Input::all();
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        return $this->makeView('errors.400', '这个动作还没有实现', 400);
    }

    /**
     * 取消咨询
     */
    public function cancel($id)
    {
        $post = $this->getQuestion($id);
        if (! $post) {
            return $post;
        }

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return in_array($post->status, [
                Post::STATUS_NEW,
                Post::STATUS_WAIT_PAY
            ]);
        });

        $rules = array(
            'post_id' => 'task_status'
        );
        $messages = array(
            'post_id.task_status' => '该咨询不可以被取消'
        );
        $input = Input::all();
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        if (in_array($post->type, [
            Post::TYPE_PAY_TEXT,
            Post::TYPE_PAY_PHONE,
            Post::TYPE_PAY_COMPANY
        ]) && $post->status != Post::STATUS_WAIT_PAY) {
            $time = time() - strtotime($post->created_at);
            if ($time < 3600) {
                return $this->makeView('errors.400', '创建后一个小时内不可以取消', 400);
            }

            // 修改订单状态，并将钱返还到用户钱包
            $post = DB::transaction(function () use ($id, $post) {
                $post->status = Post::STATUS_CANCELLED;
                $post->save();
                $order = $post->getOrder($id);
                $order->state = Order::STATE_CANCEL;
                $wallet = Wallet::getWallet($order->user_id);
                $wallet->money = $wallet->money + $order->price;
                // 更改用户的流水记录状态
                $user_walletTransaction = WalletTransaction::getWalletTransaction($order->user_id, WalletTransaction::TYPE_QUESTION, $order->id, WalletTransaction::DIRECTION_OUT);
                $user_walletTransaction->status = WalletTransaction::STATUS_FAIL;
                $user_walletTransaction->save();
                $wallet->save();
                $order->save();
                return $post;
            });
        } else {
            //todo 需要修改order 状态
            $order = $post->getOrder($id);
            $order->state = Order::STATE_CANCEL;
            $order->save();

            $post->status = Post::STATUS_CANCELLED;
            $post->save();
        }
        $questionArr = $post->toArray();
        $questionArr['status_code'] = $questionArr['status'];
        $questionArr['status'] = UtilsHelper::getPostStatusStr($questionArr['status']);
        $questionArr['post_category'] = UtilsHelper::getWorkScopeName($questionArr['post_category']);

        return $this->makeView('general.200', $questionArr, 200);
    }

    /**
     * 删除我的咨询
     */
    public function remove($id)
    {
        $post = $this->getQuestion($id);
        if (! $post) {
            return $post;
        }

        // 检查咨询的状态check status of the question
        Validator::extend('task_status', function ($attr, $value, $parameters) use ($post) {
            return (bool) in_array($post->status, [
                Post::STATUS_COMPLETE,
                Post::STATUS_CANCELLED
            ]);
        });

        $rules = array(
            'post_id' => 'task_status'
        );
        $messages = array(
            'post_id.task_status' => '该咨询不可以被取消'
        );
        $input = Input::all();
        $input['post_id'] = $id;
        $validator = Validator::make($input, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        $post->customer_visible = Post::CUSTOMER_UNVISIBLE;
        $post->status = Post::STATUS_REMOVED;
        $post->save();
        return $this->makeView('general.200', '删除成功', 200);
    }

    /**
     * 1对1及时通信的咨询接口
     */
    public function ask($post_id)
    {
        $post = Post::find($post_id);
		//Log::info($post_id."################".$post);
        $post_thred = PostThread::where('post_id', $post_id)->first();
        if (! $post || ! $post_thred) {
            return $this->makeView('errors.404', '该咨询不存在或未受理', 404);
        }
        if ($post->status != Post::STATUS_REPLIED) {
            return $this->makeView('errors.400', '该咨询状态不正确', 400);
        }
        if ($post->type != Post::TYPE_PAY_TEXT && $post->type != Post::TYPE_QUESTION) {
            return $this->makeView('errors.400', '该咨询类型不正确', 400);
        }
        $user = array();
        if (Auth::user()->id == $post->creator_id) {
            $user = User::find($post_thred->user_id);
        }
        if (Auth::user()->id == $post_thred->user_id) {
            $user = User::find($post->creator_id);
        }
        if (! $user) {
            return $this->makeView('errors.400', '联系人信息错误', 400);
        }
        $data = array();
        $data['post_id'] = $post_id;
        $data['content'] = $post->content;
        $data['title'] = $post->title;
        $data['type'] = $post->getType();
        $data['created_at'] = $post->created_at;
        $data['user_id'] = $user->id;
        $data['realname'] = $user->realname;
        $data['user_avatar'] = UtilsHelper::getImage($user->avatar, 'img/dfimg.png');
        $data['comments'] = $post->getComments();
        $data['myName'] = Auth::user()->realname;
        $data['easemob_id'] = Auth::user()->id;
        $data['easemob_pwd'] = Easemob::getPass(Auth::user());
		//Log::info("################".$data['content']);
        return $this->makeView('question.ask', $data);
    }
}
